package edu.ynu.e_platform.entities;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author manwen Yang
 */
@Entity
@Getter
@Setter
@DiscriminatorValue("0")
@EntityListeners(AuditingEntityListener.class)  //监听实体的修改
public class Customer extends User {

    @OneToMany(mappedBy = "customer",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"customer"})
    private Set<Order> orders;


    /**
     *  用户在门店创建订单
     * @param shop
     * @return order 如果在某门店存在未支付的订单，则直接返回，不存在则新建
     */
    @JsonIgnore
    public Order createOreder(Shop shop){

        Order order = findOrder(shop);
        if (order == null) {
            order = new Order();
            order.setCustomer(this);
            order.setShop(shop);
            order.setStatus(0);
        }

        return order;
    }

    /**
     *  根据商家查找未支付的订单，按题目要求同一个门店只能有一个未支付的订单
     * @param shop
     * @return order 查找该门店是否有未支付的订单，有则直接返回，没有返回null
     */
    @JsonIgnore
    private Order findOrder(Shop shop){
        //并发加锁
        AtomicReference<Order> result = new AtomicReference<>(null);
        orders.forEach(order -> {
            if(order.getShop().getId().equals(shop.getId()) && order.getStatus().equals(0)){
                result.set(order);
            }
        });
        return result.get();
    }

    /**
     *  支付订单
     * @param order
     * @return order 完成支付的订单
     */
    @JsonIgnore
    public Order payOrder(Order order){

        //未支付的订单才允许支付
        if(order.getStatus().equals(0)) {
            order.setStatus(1);
        }

        return order;
    }

}
